<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\LibApi\CqstLibController;
use App\Http\Controllers\LibApi\GshqLibController;
use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\ScoreRuleController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 用户微信信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserLibraryInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'user_account_lib';

    /**
     * 根据account_id 获取读者证号
     */
    public function getAccountByAccountId($account_id)
    {
        $account = $this->where('id', $account_id)->value('account');
        if (empty($account)) {
            return false; //未绑定
        }
        return $account;
    }
    /**
     * 根据account_id 获取读者证号
     */
    public function getAccountByAccountIds($account_id_arr)
    {
        $res = $this->select('account', 'username')->whereIn('id', $account_id_arr)->get()->toArray();
        return $res;
    }

    /**
     * 绑定读者证
     * @param
     */
    public function _add($data, $field = [])
    {
        $this->account = $data['reader_id'];
        $this->username = $data['username'];
        $this->password = $data['password'];
        $this->id_card = $data['id_card'];
        $this->sex = $data['sex'] ==  '男' ? 1 : 2;
        $this->tel = !empty($data['tel']) ? $data['tel'] : '';
        $this->type = $data['type'];
        $this->time = $data['start_time'];
        $this->end_time = $data['end_time'];
        $this->pavilion = $data['pavilion'];
        $this->pavilion_note = $data['pavilion_note'];


        //获取注册积分
        $scoreRuleObj = new ScoreRuleController();
        $score_info = $scoreRuleObj->getScoreByType(1);
        if (!empty($score_info['score'])) {
            $this->score = $score_info['score'];
        }

        $this->save();

        if (!empty($score_info['score'])) {
            //添加积分推送信息
            $scoreRuleObj->addScoreLog([
                'account_id' => $this->id,
                'score' => $score_info['score'],
                'type_id' => 1,
                'type' => $score_info['type_name'],
                'intro' => $score_info['score'] > 0 ? '绑定读者证增加 ' . $score_info['score'] . ' 积分' :  '绑定读者证减少 ' . abs($score_info['score']) . ' 积分',
            ]);
        }

        return $score_info['score'];
    }

    /**
     * 修改绑定读者证
     * @param
     */
    public function change($data, $res = null, $findWhere = [])
    {
        if (empty($res)) {
            $res = $this;

            //生成读者证二维码
            $qrCodeObj = new QrCodeController();
            $res->qr_url = $qrCodeObj->setQr($data['account'], true);
        }
        $res->account = $data['account'];
        $res->username = $data['username'];
        $res->password = !empty($data['password']) ? $data['password'] : '';
        $res->id_card = isset($data['id_card']) ? $data['id_card'] : null;
        $res->sex = $data['sex'] == '男' ? 1 : 2;
        $res->tel = !empty($data['tel']) ? $data['tel'] : '';
        $res->type = !empty($data['type']) ? $data['type'] : null;
        $res->time = !empty($data['start_time']) ? $data['start_time'] : null; //正式环境
        $res->end_time = !empty($data['end_time']) ? $data['end_time'] : null;
        $res->pavilion = !empty($data['pavilion']) ? $data['pavilion'] : null; //正式环境
        $res->pavilion_note = !empty($data['pavilion_note']) ? $data['pavilion_note'] : null;
        $res->status_card = !empty($data['status']) ? $data['status'] : null;
        $res->cash = !empty($data['cash']) ? $data['cash'] : null;
        $res->diff_money = !empty($data['diff_money']) ? $data['diff_money'] : null;

        $res->save();
        return $res->qr_url;
    }



    //判断读者证号密码是否正确 和是否绑定读者证
    public function checkAccountPwdIsNormal($user_id, $account_id = null, $status = '正常')
    {
        if (empty($account_id)) {
            //获取用户当前信息
            $user_info = UserInfo::find($user_id);

            if (empty($user_info)) {
                return '用户信息获取失败';
            }
            if (empty($user_info['account_id'])) {
                return '您当前未绑定读者证，请先绑定读者证';
            }

            $account_id = $user_info['account_id'];
        }
        $account_lib_info = UserLibraryInfo::find($account_id);
        if (empty($account_lib_info)) {
            return '读者证号获取失败，请稍后重试';
        }
        //挂失状态下，不验证
        if ($status != '挂失') {
            if ($account_lib_info['status_card'] != '有效' && $account_lib_info['status_card'] != '正常') {
                return '当前读者证状态不是有效状态';
            }
        }

        //判断读者证号的密码是否过期
        $controllerObj = new Controller();
        $libApi = $controllerObj->getLibApiObj();
        $res = $libApi->login($account_lib_info->account, $account_lib_info->password);
        if ($res['code'] == 200) {
            $account_lib_info['account_id'] = $account_lib_info['id']; //多返回一个参数
            return $account_lib_info; //读者证号账号密码正确
        }
        return '读者证密码错误';
    }

    /**
     * 后台线下荐购判断读者证号密码是否正确
     */
    public function checkAccountPwdIsNormalByAccount($account, $password)
    {
        //判断读者证号的密码是否过期
        $controllerObj = new Controller();
        $libApi = $controllerObj->getLibApiObj();
        $res = $libApi->login($account, $password);
        if ($res['code'] == 200) {
            $account_id = $this->getReaderId($account, $password, $res['content']);
            if ($account_id === false) {
                return '读者证号获取失败，请稍后重试';
            }
            return (int)$account_id; //读者证号账号密码正确
        }
        return '读者证密码错误';
    }



    /**
     * 线下荐购验证读者证正确性后，获取读者证id
     * @param $content  接口返回的读者证信息
     */
    public function getReaderId($account, $password, $content)
    {
        $controllerObj = new Controller();
        $libApi = $controllerObj->getLibApiObj();
        DB::beginTransaction();
        try {
            $userLibraryInfoModel = new UserLibraryInfo();
            $result = $userLibraryInfoModel->where('account', $account)->first();

            //获取读者证号信息
            $readerInfo = $libApi->getReaderInfo($account);
            if ($readerInfo['code'] === 200) {
                $content['cash'] = $readerInfo['content']['readerFinInfo']['depositYuan'];
                $content['diff_money'] = $readerInfo['content']['readerFinInfo']['arrearsYuan'];
            }

            // $where['reader_id'] = $account;
            // $where['password'] = $password;
            // $where['username'] = $content['username'];
            // //$userLibraryInfoModel->cash = $res['realName'];
            // $where['id_card'] = isset($content['id_card']) ? $content['id_card'] : null;
            // $where['sex'] = $content['sex'];
            // $where['tel'] = $content['tel'];
            // $where['type'] = $content['card_type'];
            // //  $where['time'] = $res['content']['createDateTime'];//测试环境
            // $where['time'] = $content['create_time']; //正式环境
            // //$userLibraryInfoModel->diff_money = $res['realName'];//这个需要在请求一个接口
            // //$userLibraryInfoModel->is_surpass = $res['realName'];
            // $where['start_time'] = !empty($content['start_time']) ? $content['start_time'] : null;
            // $where['end_time'] = !empty($content['end_time']) ? $content['end_time'] : null;
            // $where['pavilion'] = $content['pavilion'];
            // $where['pavilion_note'] = $content['pavilion_note'];
            // $where['status'] = '有效'; //状态有效
            // $where['change_time'] = date('Y-m-d H:i:s');

            $content['password'] = $password;
            if ($result) {
                $content['id'] = $result->id;
                $userLibraryInfoModel->change($content, $result);
                $account_id = $result->id;
            } else {
                $userLibraryInfoModel->change($content);
                $account_id = $userLibraryInfoModel->id;
            }

            DB::commit();
            return $account_id;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 获取用户借阅了，但是未成功录入图书馆的书籍
     * @param $is_returning  是否获取归还中的数据
     */
    public function getBorrowNotLibrary($user_id, $account_id, $is_returning = false)
    {

        $bookHomePurchaseModel = new BookHomePurchase();
        $res = $bookHomePurchaseModel->from($bookHomePurchaseModel->getTable() . ' as p')
            ->select('b.book_name', 'b.author', 'b.price', 'b.book_num', 'b.isbn', 'b.press', 'b.pre_time', 'p.barcode', 'p.create_time as borrow_time', 'p.expire_time', 'p.return_state', 'p.shop_id')
            ->join('shop_book as b', 'b.id', '=', 'p.book_id')
            ->where('p.node', 2)
            ->where(function ($query) use ($is_returning) {
                if ($is_returning) {
                    $query->orWhere('p.return_state', 1)->orWhere('p.return_state', 3);
                } else {
                    $query->where('p.return_state', 1);
                }
            })
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('p.account_id', $account_id);
                } else {
                    $query->where('p.user_id', $user_id);
                }
            })
            ->get()
            ->toArray();

        foreach ($res as $key => $val) {
            $res[$key]['book_num'] = ''; //增加元素
            $res[$key]['status'] = $val['return_state'] == 1 ? 1 : 3; //增加元素
            if ($val['shop_id']) {
                $res[$key]['shop_name'] = Shop::where('id', $val['shop_id'])->value('name');
            } else {
                $res[$key]['shop_name'] = null;
            }
        }
        return $res;
    }

    /**
     * 获取用户借阅了，但是未成功录入图书馆的书籍 已归还的数据
     * @param $account
     * @param $is_returning  是否获取归还中的数据
     */
    public function getReturnNotLibrary($user_id, $account_id)
    {
        $bookHomePurchaseModel = new BookHomePurchase();
        $res = $bookHomePurchaseModel->from($bookHomePurchaseModel->getTable() . ' as p')
            ->select('b.book_name', 'b.author', 'b.price', 'p.isbn', 'b.press', 'p.barcode', 'p.create_time as borrow_time', 'p.expire_time', 'p.return_state')
            ->join('shop_book as b', 'b.id', '=', 'p.book_id')
            ->where('p.node', 2)
            ->where('p.return_state', 2)
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('p.account_id', $account_id);
                } else {
                    $query->where('p.user_id', $user_id);
                }
            })
            ->get()
            ->toArray();
        foreach ($res as $key => $val) {
            $res[$key]['book_num'] = ''; //增加元素
        }
        return $res;
    }
    /**
     * 获取用户当前借阅 数量（包括未成功写入图书馆的数据） ， 和逾期未归还的数据
     * @param $authorrization ：用户 token
     */
    public function getNowBorrowInfo($account,  $account_id = null)
    {
        //获取馆藏书当前借阅信息
        $controllerObj = new Controller();
        $libApi = $controllerObj->getLibApiObj();
        $res = $libApi->getNowBorrowList($account, 1, 100);

        if ($res['code'] != 200) {
            $res['content'] = [];
        }
        //添加上用户失败的记录
        $result = $this->getBorrowNotLibrary(null, $account_id, false);

        $data = array_merge($res['content'], $result);
        $borrow_total = 0;
        $overdue = 0;
        foreach ($data as $key => $val) {
            $borrow_total++;
            if ($val['expire_time'] < date('Y-m-d H:i:s')) {
                $overdue++;
            }
        }

        return [$borrow_total, $overdue];
    }
    /**
     * 判断读者证是否被其他用户绑定
     */
    public function isBindAccount($account_id, $user_id = null)
    {
        $user_info = UserInfo::where('account_id', $account_id)->first();
        if ($user_info && $user_info['id'] != $user_id) {
            $nickname = UserWechatInfo::where('id', $user_info['wechat_id'])->value('nickname');
            return '此读者证号已被“' . $nickname . '“绑定，请先解绑'; //未绑定
        }
        return true;
    }



    /**
     * 查询满足要求的记录
     * @param sex 1男 2女
     * @param start_age 开始年龄    包含关系
     * @param end_age 结束年龄   2个都是 0 表示不限
     */
    public function getConformData($sex, $start_age, $end_age)
    {
        $where = "id > 1";
        if ($start_age || $end_age) {
            if ($start_age && !$end_age) {
                $where = "age => $start_age";
            } elseif (!$start_age && $end_age) {
                $where = "age => $start_age";
            } elseif ($start_age == $end_age) {
                $where = "age = $start_age";
            } else {
                $where = "age >= $start_age && age <= $end_age";
            }
        }
        $data = $this->select('id', 'card', DB::raw('substring(now(),1,4)-substring(card,7,4))-(substring(card,11,4)- date_format(now(),\'%m%d\')>0) as age'))
            ->where(function ($query) use ($sex) {
                if ($sex) {
                    $query->where('sex', $sex);
                }
            })
            ->having($where)
            ->get()
            ->toArray();

        return $data;
    }
}
